package com.example.demo.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.demo.entity.User;
import com.example.demo.exception.CmsException;
import com.example.demo.exception.ErrorCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @author chen huilong
 * @data 2022/10/19
 */
public class UserLoginInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        String access_token = request.getHeader("access_token");
        //如果token为空
        if (StringUtils.isBlank(access_token)) {
            throw new CmsException(ErrorCode.SESSION_IS_EXPIRED);
        }
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(access_token);
        if (user == null) {
            throw new CmsException(ErrorCode.SESSION_IS_EXPIRED);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }

}
